package com.fresh.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fresh.common.ResponseResult;
import com.fresh.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入过滤器");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if(request.getURI().getPath().contains("/login")){
            System.out.println("/login请求直接放行");
            return chain.filter((exchange));
        }
        System.out.println("其他请求必须登录后才能访问,验证token");
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)||!JwtUtil.verify(token)){

            System.out.println("token无效,拦截");
            byte[] bytes = null;
            try {
                bytes = new ObjectMapper().writeValueAsBytes(new ResponseResult<>(401,"ok","login first先登录"));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            response.getHeaders().add("content-type","application/json;charset=utf-8");
            DataBuffer data = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(data));
        }
        System.out.println("token有效,放行");
        /*if(StringUtils.isEmpty(request.getQueryParams().getFirst("userName"))){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }*/
        Integer uid = 1;//JwtUtil.getUid(token);
        ServerHttpRequest newReq = exchange.getRequest().mutate().header("userId", uid.toString()).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(newReq).build();
        return chain.filter(mutableExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
